package sk.naive.talker.props;

import sk.naive.talker.util.Utils;

import java.util.*;

/**
 * MacrosProperty helps store and load macros in a string (db) or in a map (runtime).
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.5 $ $Date: 2004/10/24 15:58:47 $
 */
public class MacrosProperty extends SimpleProperty {
	public String toString(Object o) {
		Map<String,String> macros = (Map<String,String>) o;
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String,String> entry : macros.entrySet()) {
			if (sb.length() > 0) {
				sb.append("\n");
			}
			sb.append(Utils.mapKeyQuote(entry.getKey()) + "=" + entry.getValue());
		}
		return sb.toString();
	}

	public Object toObject(String s) {
		Map<String,String> macros = new TreeMap<String,String>();
		if (s == null) {
			return macros;
		}
		for (String pairString : s.split("\\n")) {
			String[] sa = pairString.split("=", 2);
			if (sa.length == 2) {
				macros.put(Utils.mapKeyUnqote(sa[0]), sa[1]);
			}
		}
		return macros;
	}

	public Object defaultValue() {
		return new TreeMap();
	}
}
